(function () {
	ko.simpleGrid = {

		// Defines a view model class you can use to populate a grid
		viewModel: function (configuration) {
			/************************
			Private Functions
			************************/
			function setTHClass(event) {
				//remove the existing classes
				$("div.title").find(".sort_column").children("a").removeClass("asc");
				$("div.title").find(".sort_column").children("a").removeClass("desc");

			}

			function switchSortOrder() {
				if (this.sortOrder === "asc") {
					this.sortOrder = "desc";
				} else {
					this.sortOrder = "asc";
				}
			}
			function SetOrder(event, colName) {
				switchSortOrder();
				setTHClass(event);
				if (colName != "") {
					this.data(SortByPropertyName(ko.utils.unwrapObservable(this.data()), colName, sortOrder));
					// Set current column sorted
					if (this.sortOrder === "asc") {
						$('#' + colName).find("a").addClass("desc");
						this.sortOrder = "desc";
					} else {
						$('#' + colName).find("a").addClass("asc");
						this.sortOrder = "asc";
					}
				}
			}

			// sort all items
			function SortByPropertyName(items, propertyName, sortOrder) {
				return items.sort(sortProperty(propertyName, sortOrder));
			}
			function sortProperty(property, sortOrder) {
				if (sortOrder == "asc")
					return function (a, b) {
						var number = parseFloat(a[property].toLowerCase());
						if (number != NaN && number > 0)
							return (parseFloat(a[property].toLowerCase()) < parseFloat(b[property].toLowerCase())) ? -1 : (parseFloat(a[property].toLowerCase()) > parseFloat(b[property].toLowerCase())) ? 1 : 0;
						else
							return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0;
					}
				else
					return function (a, b) {
						var number = parseFloat(a[property].toLowerCase());
						if (number > 0)
							return (parseFloat(a[property].toLowerCase()) > parseFloat(b[property].toLowerCase())) ? -1 : (parseFloat(a[property].toLowerCase()) < parseFloat(b[property].toLowerCase())) ? 1 : 0;
						else
							return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0;
					}

			}


			this.SetOrder = SetOrder;
			this.colName = "";
			this.sortOrder = ko.observable("asc");
			this.data = ko.observableArray(configuration.data);
			this.currentPageIndex = ko.observable(1);
			this.pageSize = ko.observable(parseInt(configuration.pageSize || 5));
			this.previousText = ko.observable("Prev");
			this.nextText = ko.observable("Next");

			// If you don't specify columns configuration, we'll use scaffolding
			this.columns = configuration.columns;

			this.outerWidth = ko.computed(function () {
				return Math.ceil(this.columns().length * 150) + "px";
			}, this);

			this.maxPageIndex = ko.computed(function () {
				if (this.pageSize() == 0)
					return 0;
				else
					return Math.ceil(ko.utils.unwrapObservable(this.data()).length / this.pageSize());
			}, this);

			this.itemsOnCurrentPage = ko.computed(function () {
				var pagevalue = this.pageSize().toString().replace(/\s/g, '');
				var pagesize = parseInt(pagevalue, 10);

				if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
					return "";
				}
				else {
					var startIndex = this.pageSize() * (this.currentPageIndex() - 1);
					var endIndex = parseInt(startIndex) + parseInt(this.pageSize());

					return this.data().slice(startIndex, endIndex);
				}
			}, this);



			/////////////////////// PAGING /////////////////////////////
			this.PageSizeText = ko.computed(function () {
				if (ko.utils.unwrapObservable(this.data()).length > 0) {
					var pagevalue = this.pageSize().toString().replace(/\s/g, '');
					var pagesize = parseInt(pagevalue, 10);
					this.currentPageIndex(1);
					if (!IsNumeric(pagevalue))
						return "* Please enter a number between 1 - 100";
					else if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
						return "* Please enter a number between 1 - 100";
					}
					else {
						return "";
					}
				}

			}, this);
			this.PageCurrentText = ko.computed(function () {
				if (ko.utils.unwrapObservable(this.data()).length > 0) {
					var pagevalue = this.currentPageIndex().toString().replace(/\s/g, '');
					var pageindex = parseInt(pagevalue, 10);
					if (parseInt(this.pageSize().toString().replace(/\s/g, ''), 10) == 0)
						return "";
					else if (!IsNumeric(this.currentPageIndex()) || pagevalue == "")
						return "* Please enter a number between 1 - " + this.maxPageIndex() + " ";
					else if (pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.maxPageIndex()) {
						return "* Please enter a number between 1 - " + this.maxPageIndex() + " ";
					}
					else {
						return "";
					}
				}
				else {
					return "";
				}

			}, this);

			this.PreviousPage = function () {
				var page = parseInt(this.currentPageIndex());
				if (page > 1) {
					this.currentPageIndex(page - 1);
				}
			}
			this.NextPage = function () {
				var page = parseInt(this.currentPageIndex());
				if (page < this.maxPageIndex()) {
					this.currentPageIndex(page + 1);
				}
			}
			this.previousClass = ko.computed(function () {
				var page = parseInt(this.currentPageIndex());
				if (page > 1) {
					return "btn btn-prev-arrow prev-active";
				}
				else {
					return "btn btn-prev-arrow";
				}
			}, this);

			this.nextClass = ko.computed(function () {
				if (this.currentPageIndex() >= this.maxPageIndex() || this.maxPageIndex() == 1) {
					return "btn btn-next-arrow next-disabled";
				}
				else {
					return "btn btn-next-arrow";
				}
			}, this);
		}
	};

	// Templates used to render the grid
	var templateEngine = new ko.nativeTemplateEngine();

	templateEngine.addTemplate = function (templateName, templateMarkup) {
		document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
	};

	var gridHeader = "<span class=\"paging\">";
	gridHeader += "<span class=\"show\">";
	gridHeader += "Show <input class='text' id='pagesize' value=\"10\" onkeypress='return isNumberKey(event)' data-bind=\"value: pageSize, attr:{type: 'text', maxlength: 3} \" /> per page";
	gridHeader += "<span class=\"smallText\" data-bind=\"text: PageSizeText\">";
	gridHeader += "</span>";
	gridHeader += "</span>";

	gridHeader += "<span class=\"pages\">";
	gridHeader += "<span class=\"smallText\" data-bind=\"text: PageCurrentText\">";
	gridHeader += "</span>";
	gridHeader += "Page <input class='text' id='pagecurrent' value=\"1\" onkeypress='return isNumberKey(event)' data-bind=\"value: currentPageIndex, attr: {type: 'text', maxlength: 2} \" /> of <span data-bind=\"text: maxPageIndex() \"></span>";
	gridHeader += " <a href=\"##\" data-bind=\"text: previousText, click: function() { $root.PreviousPage() }, attr: {'class': previousClass} \">Previous</a>";
	gridHeader += " <a href=\"##\" data-bind=\"text: nextText, click: function() { $root.NextPage() } , attr: {'class': nextClass} \"></a>";
	gridHeader += "</span>";
	gridHeader += "</span>";

	templateEngine.addTemplate("ko_simpleGrid_pageLinks", gridHeader);

	// Remove all [style="height:31px;"] for each table rows
	templateEngine.addTemplate("ko_simpleGrid_grid", "\
		<div class=\"table table-leads leadfunnel table-horscroll\" style=\"width: 1015px\">\
			<div class='title' data-bind=\"style: {width: $root.outerWidth()}, foreach: columns\">\
				<div class='col1' style=\"width:150px\" data-bind=\"attr: {id: columName} \">\
					<span class=\"w sort_column\"><a href=\"##\" class=\"sort\" data-bind=\"text: headerText, click: function(event) { $root.SetOrder(event, columName) } \"></a></span>\
				</div>\
			</div>\
			<div class=\"linegroup\" data-bind=\"style: {width: $root.outerWidth()}, foreach: itemsOnCurrentPage\">\
				<div class='line' data-bind=\"style: {width: $root.outerWidth()}, foreach: $parent.columns\">\
					<div class=\"col1\" style=\"width:150px;\"><span class=\"w\" data-bind=\"html: typeof rowText == 'function' ? rowText($parent) : $parent[rowText] \"></span></div>\
				</div>\
			</div>\
		</div>");

	// The "simpleGrid" binding
	ko.bindingHandlers.simpleGrid = {
		init: function () {
			return { 'controlsDescendantBindings': true };
		},
		// This method is called to initialize the node, and will also be called again if you change what the grid is bound to
		update: function (element, viewModelAccessor, allBindingsAccessor) {
			var viewModel = viewModelAccessor(), allBindings = allBindingsAccessor();

			// Empty the element
			while (element.firstChild)
				ko.removeNode(element.firstChild);

			// Allow the default templates to be overridden
			var gridTemplateName = allBindings.simpleGridTemplate || "ko_simpleGrid_grid",
				pageLinksTemplateName = allBindings.simpleGridPagerTemplate || "ko_simpleGrid_pageLinks";

			// Render the page links
			var pageLinksContainer = element.appendChild(document.createElement("DIV"));
			ko.renderTemplate(pageLinksTemplateName, viewModel, { templateEngine: templateEngine }, pageLinksContainer, "replaceNode");

			// Render the main grid
			var gridContainer = element.appendChild(document.createElement("DIV"));
			ko.renderTemplate(gridTemplateName, viewModel, { templateEngine: templateEngine }, gridContainer, "replaceNode");
		}
	};


})();

$('body').ready(function () {
	$('#startDate').removeClass('text-active');
	$('#endDate').removeClass('text-active');
	$('#startDate').focus(function () {
		$('#startDate').addClass('text-active');
	});
	$('#endDate').focus(function () {
		$('#endDate').addClass('text-active');
	});
	$('#startDate').blur(function () {
		setTimeout(function () {
			$('#startDate').removeClass('text-active');
			if (!isDateUS($('#startDate').val())) {
				$('#startDate').val(getCurrentDate());
			}
		}, 1);
	});
	$('#endDate').blur(function () {
		setTimeout(function () {
			$('#endDate').removeClass('text-active');
			if (!isDateUS($('#endDate').val())) {
				$('#endDate').val(getCurrentDate());
			}
		}, 1);
	});
});
